package org.school.controller;

import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.school.entity.*;
import org.school.service.HostService;
import org.school.service.ShopService;
import org.school.service.UserService;
import org.school.staticException.PasswordIncorrectException;
import org.school.staticException.UserNotFoundException;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
@Log4j2
@RestController
@CrossOrigin
public class RegisterController {
    @Resource
    private UserService userService;
    @Resource
    private HostService hostService;
    @Resource
    private ShopService shopService;
    @PostMapping("regUser")
    public ResponseEntity register (@RequestBody
                                       @Validated User regUser, BindingResult bindingResult) throws IOException, UserNotFoundException, PasswordIncorrectException {//用户注册功能
        List<ObjectError> allErrors=bindingResult.getAllErrors();
        allErrors.forEach(error->log.error("用户登录时校验失败:{}",error.getDefaultMessage()));
        if (allErrors.size()>0){
            return  ResponseEntity.status(500).build();
        }
        message message = userService.register(regUser);
        return ResponseEntity.ok().body(message);
    }
    @PostMapping("regHost")
    public ResponseEntity registerHost (@RequestBody
                                          @Validated Host regHost, BindingResult bindingResult) throws IOException, UserNotFoundException, PasswordIncorrectException {//用户注册功能
        List<ObjectError> allErrors=bindingResult.getAllErrors();
        allErrors.forEach(error->log.error("用户登录时校验失败:{}",error.getDefaultMessage()));
        if (allErrors.size()>0){
            return  ResponseEntity.status(500).build();
        }
        message mes = hostService.register(regHost);
        if(mes.getStatus()!=1){
            return ResponseEntity.ok().body(mes);
        }
        Shop shop=new Shop();
        shop.setHost(regHost.getUsername());
        shop.setName(regHost.getShopnumber());
         int i=shopService.insert(shop).getId();
        if(i<0){
             mes.setContent("创建用户成功,商店创建失败");
             mes.setStatus(0);
         }else {
          mes.setContent("创建用户和商店成功");
          mes.setStatus(1);
        }
        return ResponseEntity.ok().body(mes);
    }
}
